package com.acxiom.bsh.service.impl;

import java.net.URLDecoder;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.acxiom.bsh.constants.CommonConstant;
import com.acxiom.bsh.constants.ThreadLocalContextHolder;
import com.acxiom.bsh.dao.CommoDao;
import com.acxiom.bsh.dao.LuckydrawDao;
import com.acxiom.bsh.entity.Customer;
import com.acxiom.bsh.entity.DrawResult;
import com.acxiom.bsh.exception.BshException;
import com.acxiom.bsh.exception.ExceptionBuilder;
import com.acxiom.bsh.logger.LoggerManager;
import com.acxiom.bsh.pojo.CardPool;
import com.acxiom.bsh.pojo.KeyValue;
import com.acxiom.bsh.pojo.LltPojo;
import com.acxiom.bsh.pojo.Prize;
import com.acxiom.bsh.pojo.PrizeRecord;
import com.acxiom.bsh.pojo.SParameter;
import com.acxiom.bsh.request.CommonApiRequest;
import com.acxiom.bsh.request.PointRequest;
import com.acxiom.bsh.request.SmsRequest;
import com.acxiom.bsh.response.ApiResponse;
import com.acxiom.bsh.service.ApiService;
import com.acxiom.bsh.service.LuckydrawService;
import com.acxiom.bsh.util.CommonUtils;
import com.acxiom.bsh.util.LltUtil;
import com.acxiom.bsh.util.Md5Util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@Service
public class LuckydrawServiceImpl implements LuckydrawService {

	@Autowired
	private CommoDao commonDao;

	@Autowired
	LuckydrawDao luckyDrawDao;

	@Autowired
	ApiService apiService;
	
	@Value("${llt.account}")
	private String account;
	
	@Value("${llt.appKey}")
	private String appKey;

	
	/**
	 * 抽奖用的service
	 */
	@Override
	// @Transactional(propagation = Propagation.REQUIRED, rollbackFor =
	// BshException.class)
	public DrawResult draw(String mixNick) throws BshException {
		DrawResult result = new DrawResult();

		if (!validateDrawTimes(mixNick, result)) {
			return result;
		}
		//获取用户信息
		Customer customer = getCustomer(mixNick, result);
		if (customer == null) {
			return result;

		}
		//开始抽奖
		Prize prize = draw(mixNick, result, customer);
		if (prize == null) {
			return result;
		}
		reducePoint(mixNick, result);
		if (!result.isSuccess()) {
			return result;
		}
		//如果抽奖的奖品是优酷 就开始发送优酷短信
		/*if (prize.getPrizeLevel() == 4) {
			boolean flag = sendSMSPrize(mixNick);
			if (flag) {
				LoggerManager.getApiLogger().info("youku prize send sms successfully.");
			}
		}*/
		
		//当奖品是积分的话 就开始给予积分
		if (prize.getGiftType() == 1) {
			addPoint(mixNick, prize.getPointCode(), result);
			if (!result.isSuccess()) {
				return result;
			}
		}

		return result;
	}

	@Override
	public List<PrizeRecord> getPrizeList(String mixNick) {

		try {
			return luckyDrawDao.getPrizeRecord(mixNick);
		} catch (Exception e) {
			LoggerManager.getErrorLogger().error("Services getPrizeList error", e);
		}
		return null;

	}

	/**
	 * validate current day draw times, can not exceed the max draw times
	 * 
	 * @param mixNick
	 * @param result
	 * @return
	 * @throws BshException
	 */
	private boolean validateDrawTimes(String mixNick, DrawResult result) throws BshException {

		try {
			int drawDailyTimes = Integer.parseInt(commonDao.getSparameter("DRAW_DAILY_TIMES"));

			int currentDayDrawTimes = luckyDrawDao.getCurrentDayDrawTimes(mixNick);
			if (currentDayDrawTimes >= drawDailyTimes) {
				result.setSuccess(false);
				result.setCode("001");
				result.setMessage("超过最大抽奖次数");
				return false;
			}
			return true;
		} catch (Exception e) {
			LoggerManager.getErrorLogger().error("Services validateDrawTimes error", e);
			throw ExceptionBuilder.buildException("092", "当前系统繁忙，请稍后再试", e);
		}
	}

	/**
	 * validate current day validate1234PrizeTimes times, can not exceed the max
	 * draw times
	 * 
	 * @param mixNick
	 * @param result
	 * @return
	 * @throws BshException
	 */
	private boolean validate1234PrizeTimes(String mixNick, DrawResult result, Prize prize) throws BshException {

		try {
			int drawDailyTimes = Integer.parseInt(commonDao.getSparameter("1234_DRAW_DAILY_TIMES"));

			int currentDayDrawTimes = luckyDrawDao.getCurrentDay1234PrizeTimes(mixNick, prize.getId());
			if (currentDayDrawTimes >= drawDailyTimes) {
				return true;
			}
			return false;
		} catch (Exception e) {
			LoggerManager.getErrorLogger().error("Services validate1234PrizeTimes error", e);
			throw ExceptionBuilder.buildException("092", "当前系统繁忙，请稍后再试", e);
		}
	}

	private Customer getCustomer(String mixNick, DrawResult result) throws BshException {
		Customer customer = null;
		String path = String.format("member?iSN=%d&mix_taobaoId=%s", System.currentTimeMillis(), mixNick);
		ApiResponse response = null;
		Object object = null;
		try {
			response = apiService.get(path);
			if (response == null) {
				LoggerManager.getErrorLogger().error("Services getCustomer response is null");
				throw ExceptionBuilder.buildException("091", "当前系统繁忙，请稍后再试");
			}
		} catch (Exception e) {
			LoggerManager.getErrorLogger().error("Services getCustomer Error ", e);
			throw ExceptionBuilder.buildException("090", "当前系统繁忙，请稍后再试", e);
		}
		if (response != null & response.getData() != null) {
			object = response.getData();
			customer = (Customer) JSONObject.parseObject(JSONObject.toJSONString(object), Customer.class);
		} else {
			throw ExceptionBuilder.buildException("003", "会员不存在");
		}

		return customer;
	}

	private Prize draw(String mixNick, DrawResult result, Customer customer) throws BshException {
		Prize resultPrize = null;

		try {
			Random rand = new Random();
			double num = rand.nextDouble();
			resultPrize = null;

			//查询已经抽过的次数
			int totalDrawTimes = luckyDrawDao.getTotalDrawTimes(mixNick);

			double lastProbability = 0;
			double currentProbability = 0;
			double nextProbability = 0;
			
			//奖品列表
			List<Prize> prizeList = luckyDrawDao.getPrize();
			for (Prize prize : prizeList) {
				
				//当前的抽奖概率
				currentProbability = prize.getProbability();

				nextProbability = lastProbability + currentProbability;

				if (num >= lastProbability && num < nextProbability) {
					lastProbability = nextProbability;
					num = nextProbability;
					//当用户等级为1并且这个奖品需要购买
					if ((StringUtils.isEmpty(customer.getTier()) || customer.getTier().equals("1")) && prize.getNeedPurchase() == 1) {
						continue;
					}

					if (totalDrawTimes < prize.getMinTimes()) {
						continue;
					}
					//验证是否有单笔交易大于100块的
//					if (prize.getPrizeLevel() == 1 || prize.getPrizeLevel() == 2 || prize.getPrizeLevel() == 3) {
//						if (!validateNeedPurchase(mixNick, prize)) {
//							continue;
//						}
//					}
					//抽奖得到优酷会员
//					if (prize.getPrizeLevel() == 4) {
//						CardPool cardPool = luckyDrawDao.getCard();
//						if (cardPool == null || cardPool.getCardNo() == null) {
//							LoggerManager.getApiLogger().info("YouKu cardpool has not useful cardNo!");
//							continue;
//						}
//					}
					//每个用户只能抽到一个1 2 3 4奖品
					if (prize.getPrizeLevel() == 1 || prize.getPrizeLevel() == 2 || prize.getPrizeLevel() == 3 || prize.getPrizeLevel() == 4) {
						if (validate1234PrizeTimes(mixNick, result, prize)) {
							continue;
						}
					}
					
					//减少奖品库存 
					int updateSize = luckyDrawDao.updateInventory(prize);
					if (updateSize == 0) {
						continue;
					} else {
						//塞入成功抽到的奖品
						drawSuccess(result, prize);
						PrizeRecord record = new PrizeRecord();
						record.setMixNick(mixNick);
						record.setPrizeId(prize.getId());
						record.setPrizeName(prize.getGiftName());
						String sellerName = URLDecoder.decode(ThreadLocalContextHolder.get().getValue(), "UTF-8");
						record.setSellerName(sellerName);
						record.setStatus(0);
						//抽奖得到100M流量 并且有手机号的时候开始发送流量
						if (prize.getPrizeLevel() == 4 && customer!=null && CommonUtils.isNotEmpty(customer.getTel())) {
							LltPojo lltPojo = new LltPojo();
							lltPojo.setAccount(account);
							lltPojo.setMobile(customer.getTel());
							lltPojo.setAppKey(appKey);
							String lltResult = LltUtil.rechargeFlow(lltPojo);
							JSONObject json = JSONObject.parseObject(lltResult);
							LoggerManager.getApiLogger().info("流量通流量充值结果==》"+lltResult);
							//代表流量充值成功
							if(json.get("Code").toString().equals("0")){
								record.setStatus(2);
							}else{
								record.setStatus(1);
							}
						}
						luckyDrawDao.savePrizeRecord(record);
						resultPrize = prize;
						break;
					}
				}
				lastProbability = lastProbability + currentProbability;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw ExceptionBuilder.buildException("097", "当前系统繁忙，请稍后再试", e);
		}

		try {
			if (resultPrize == null) {
				//当抽奖结果为空 默认塞入一个奖品 当前是50积分
				resultPrize = luckyDrawDao.getDefaultPrize();
				luckyDrawDao.updateInventory(resultPrize);
				PrizeRecord record = new PrizeRecord();
				record.setMixNick(mixNick);
				record.setPrizeId(resultPrize.getId());
				record.setPrizeName(resultPrize.getGiftName());
				luckyDrawDao.savePrizeRecord(record);
				drawSuccess(result, resultPrize);
			}
		} catch (Exception e) {
			LoggerManager.getErrorLogger().error("getDefaultPrize  Prize Error", e);
			throw ExceptionBuilder.buildException("098", "当前系统繁忙，请稍后再试", e);
		}

		return resultPrize;

	}

	private void drawSuccess(DrawResult result, Prize prize) {
		result.setSuccess(true);
		result.setCode(prize.getId().toString());
		result.setPrizeLevel(prize.getPrizeLevel());
		result.setPrizeName(prize.getGiftName());
		result.setPrizeDescription(prize.getGiftDescription());
	}

	private void addPoint(String mixNick, String pointCode, DrawResult result) throws BshException {

		PointRequest request = new PointRequest();
		request.setEventCode(pointCode);
		request.setMix_taobaoId(mixNick);
		request.setiSN(System.currentTimeMillis());
		request.setEventMemo("Lucky Draw add Points");

		ApiResponse response = null;
		try {
			response = point(request);
			if (response == null) {
				throw ExceptionBuilder.buildException("0096", "当前系统繁忙，请稍后再试");
			}
		} catch (BshException e) {
			throw ExceptionBuilder.buildException("0096", "当前系统繁忙，请稍后再试", e);
		}

	}

	private void reducePoint(String mixNick, DrawResult result) throws BshException {
		String pointCode = commonDao.getSparameter("LUCKY_DRAW_POINT_CODE");

		PointRequest request = new PointRequest();
		request.setEventCode(pointCode);
		request.setMix_taobaoId(mixNick);
		request.setiSN(System.currentTimeMillis());
		request.setEventMemo("Lucky Draw add Points");

		ApiResponse response = null;
		try {
			response = point(request);
			if (response == null) {
				throw ExceptionBuilder.buildException("095", "当前系统繁忙，请稍后再试");
			}
		} catch (BshException e) {
			throw ExceptionBuilder.buildException("094", "当前系统繁忙，请稍后再试", e);
		}

	}

	private ApiResponse point(PointRequest request) throws BshException {

		ApiResponse response = null;
		try {
			response = apiService.post("point", request);
			return response;
		} catch (Exception e) {
			throw ExceptionBuilder.buildException("093", "当前系统繁忙，请稍后再试", e);
		}
	}

	@Override
	public List<PrizeRecord> getPrizeListTop5() throws BshException {
		List<PrizeRecord> prizeTop5 = null;
		try {
			prizeTop5 = luckyDrawDao.getPrizeListTop5();
		} catch (Exception e) {
			e.printStackTrace();
			throw ExceptionBuilder.buildException("093", "当前系统繁忙，请稍后再试", e);
		}
		return prizeTop5;
	}

	/**
	 * 验证是否有单笔交易大于100块的
	 * 
	 * @param mixNick
	 * @param prize
	 * @return
	 * @throws BshException
	 */
	public boolean validateNeedPurchase(String mixNick, Prize prize) {
		CommonApiRequest request = new CommonApiRequest();

		request.setMix_taobaoId(mixNick);
		request.setiSN(System.currentTimeMillis());

		ApiResponse response = null;
		try {
			response = apiService.get("purchase/checkPurchaseAmountOver100", new KeyValue("iSN", Long.toString(System.currentTimeMillis())), new KeyValue("mix_taobaoId", mixNick));
			if (response == null) {
				ExceptionBuilder.buildException("0096", "当前系统繁忙，请稍后再试");
				return false;
			}
			if (!response.getMeta().isSuccess()) {
				return false;
			}
			return Boolean.parseBoolean(JSON.toJSONString(response.getData()));

		} catch (Exception e) {
			ExceptionBuilder.buildException("0096", "当前系统繁忙，请稍后再试", e);
			return false;
		}

	}

	public boolean sendSMSPrize(String mixNick) {
		boolean flag = false;
		SmsRequest request = new SmsRequest();
		String path = "sms";
		try {
			String cardNo = luckyDrawDao.updateUsedCard(mixNick);
			SParameter sParameter = luckyDrawDao.getSParameter(CommonConstant.SPARAMETER_LUCKYDRAW_SMS);
			if (!StringUtils.isBlank(cardNo)) {
				request.setMix_taobaoId(mixNick);
				request.setiSN(System.currentTimeMillis());
				request.setMessage(sParameter.getValue().replace("##", cardNo));
				ApiResponse response = apiService.post(path, request);
				if (response != null && response.getMeta().isSuccess()) {
					flag = true;
				}
			} else {
				LoggerManager.getErrorLogger().error("YouKu cardpool has not useful cardNo!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			LoggerManager.getErrorLogger().error("Sms send failed!");
			flag = false;
		}
		return flag;
	}
	
	

}